import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {Form} from "antd";
import {query} from "./actions";
import {DATE_FORMAT} from "../../lib/func";
import FilterForm from "../../components/FilterForm";
import {getLastFilter, getPrincipal, saveLastFilter} from "../../lib/identity";

const LAST_FILTER = "historyNotice";

class Filter extends PureComponent {
    state = {};
    handleSearch = (values) => {
        const {dispatch, pageSize, filter} = this.props;
        let fields = values;
        this.setState({...fields});
        if (fields.createTimeRange && fields.createTimeRange.length > 1) {
            fields.createTimeStart = fields.createTimeRange[0].format(DATE_FORMAT);
            fields.createTimeEnd = fields.createTimeRange[1].format(DATE_FORMAT);
        } else {
            fields.createTimeStart = undefined;
            fields.createTimeEnd = undefined;
        }
        fields.userId = getPrincipal().id;
        delete fields.createTimeRange;
        saveLastFilter(LAST_FILTER, {...fields});
        dispatch(query({
            ...fields,
            filter: {...filter, ...fields},
            page: 1,
            pageSize
        }));
    };

    render() {
        const {loading} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        const filterSchema = [
            {
                key: 'createTimeRange',
                field: 'createTimeRange',
                type: 'dateRangePicker',
                expandable: true,
                title: '创建日期',
                fieldOptions: {
                    initialValue: this.state.createTimeRange || fields.createTimeRange
                }
            }
        ];
        return (
            <FilterForm schema={filterSchema} callback={this.handleSearch} loading={loading}/>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.historyNotice.list
    };
};

export default connect(mapStateToProps)(Form.create()(Filter));
